﻿using HBKY.Shop.Common.LogHelper;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HBKY.Shop.Common.Helper
{
    /// <summary>
    /// 重试帮助类
    /// </summary>
    public class RetryHelper
    {
        /// <summary>
        /// 默认重试3次
        /// </summary>
        private static T Retry<T>(Func<T> func, int retyTimes = 3)
        {
            return Retry(func, 0, retyTimes);
        }

        /// <summary>
        /// 不带返回值的
        /// </summary>
        /// <param name="func"></param>
        /// <param name="retyTimes"></param>
        private static void Retry(Action func, int retyTimes = 3)
        {
            Retry(() => { func.Invoke(); return string.Empty; }, retyTimes);
        }

        /// <summary>
        /// 操作重试
        /// </summary>
        private static T Retry<T>(Func<T> func, int retriedTimes, int maxRetryTime)
        {
            try
            {
                return func.Invoke();
            }
            catch (SocketException ex)
            {
                // 如果重试成功了其实记不记无所谓，这里只记个Debug
                LogManagerNlog.LogDebug($"Failed at RedisWrapper, with {maxRetryTime - retriedTimes} chances left to retry.", ex);
                if (retriedTimes < maxRetryTime) { retriedTimes++; Thread.Sleep(500); return Retry(func, retriedTimes, maxRetryTime); }
                else { LogManagerNlog.LogError($"Failed at RedisWrapper even retried for {maxRetryTime} times!", ex); throw; }
            }
            catch(Exception ex)
            {
                LogManagerNlog.LogError(ex,$"Failed at RedisWrapper, with {maxRetryTime - retriedTimes} chances left to retry.");
            }
            return default;
        }

    }
}
